import 'package:dio/dio.dart';

class HttpUtil {
  static HttpUtil? _instance;
  late Dio dio;
  late BaseOptions options;
  CancelToken cancelToken = CancelToken();

  static HttpUtil getInstance() {
    _instance ??= HttpUtil._();
    return _instance!;
  }

  static Future<void> init() async {
    getInstance();
  }

  factory HttpUtil() => _instance ?? HttpUtil._();

  HttpUtil._() {
    //BaseOptions、Options、RequestOptions 都可以配置参数，优先级别依次递增，且可以根据优先级别覆盖参数
    options = BaseOptions(
      //请求基地址,可以包含子路径
      baseUrl: "",
      //连接服务器超时时间
      connectTimeout: const Duration(seconds: 10),
      //响应流上前后两次接受到数据的间隔
      receiveTimeout: const Duration(seconds: 10),
      //Http请求头.
      headers: {
        //do something
        "version": "1.0.0"
      },
      //请求的Content-Type，默认值是"application/json; charset=utf-8",Headers.formUrlEncodedContentType会自动编码请求体.
      contentType: Headers.formUrlEncodedContentType,
      //表示期望以那种格式(方式)接受响应数据。接受4种类型 `json`, `stream`, `plain`, `bytes`. 默认值是 `json`,
      responseType: ResponseType.json,
    );
    dio = Dio(options);
  }

  /*
   * get请求
   */
  Future<Response> get(url, {data, options, cancelToken}) async {
    Response response;
    try {
      response = await dio.get(url,
          queryParameters: data, options: options, cancelToken: cancelToken);
      print('[HTTP]get success---------${response.statusCode}');
      print('[HTTP]get success---------${response.data}');
      return response;
    } on DioException catch (e) {
      print('[HTTP]get error---------');
      return formatError(e);
    }
  }

  /*
   * post请求
   */
  Future<Response> post(url, {data, options, cancelToken}) async {
    Response response;
    try {
      response = await dio.post(url,
          data: data, options: options, cancelToken: cancelToken);
      print('[HTTP]post success---------${response.statusCode}');
      print('[HTTP]post success---------${response.data}');
      return response;
    } on DioException catch (e) {
      print('[HTTP]post error---------');
      return formatError(e);
    }
  }

  /*
   * error统一处理
   */
  Response formatError(DioException e) {
    print('[HTTP]post error---------${e.type}-${e.message}');
    return Response(
      requestOptions: e.requestOptions,
      statusMessage: e.type.name,
      statusCode: e.type.index,
    );
  }
}
